package hxy.cupb.springboot.common.exception;

import hxy.cupb.springboot.entity.vo.BaseResponseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * @author LiJing
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常处理器
 * @date 2019/7/30 13:57
 */
// 返回页面
//@ControllerAdvice
//    返回json
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static int DUPLICATE_KEY_CODE = 1001;
    private static int PARAM_FAIL_CODE = 1002;
    private static int VALIDATION_CODE = 1003;


    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponseVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        return new BaseResponseVO(PARAM_FAIL_CODE, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public BaseResponseVO handleValidationException(ValidationException e) {
        logger.error(e.getMessage(), e);
        return new BaseResponseVO(VALIDATION_CODE, e.getCause().getMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponseVO handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage(), e);
        return new BaseResponseVO(PARAM_FAIL_CODE, e.getMessage());
    }

    //    @ExceptionHandler(NoHandlerFoundException.class)
//    @ExceptionHandler(value = { Exception404.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public BaseResponseVO handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return new BaseResponseVO(HttpStatus.NOT_FOUND.value(), "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public BaseResponseVO handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return new BaseResponseVO(DUPLICATE_KEY_CODE, "数据重复，请检查后提交");
    }

    @ExceptionHandler(Exception.class)
    public BaseResponseVO handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return new BaseResponseVO(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统繁忙,请稍后再试");
    }
}